package org.cmg.study.spring;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author CMG
 * @version 1.0
 * @cLassName CglibProxy
 * @description CGLIB动态代理，实现MethodInterceptor接口
 * @date 2021/9/1 10:32
 **/
public class CglibProxy implements MethodInterceptor {
    /**
     * 需要代理的目标对象
     */
    private Object target;
    final MyAspect myAspect = new MyAspect();

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        myAspect.myBefore();
        // 方法执行，参数：target目标对象 arr参数数组
        Object invoke = method.invoke(target, objects);
        myAspect.myAfter();
        return invoke;
    }

    /**
     * 定义获取代理对象方法
     * @param objectTarget
     * @return
     */
    public Object getCglibProxy(Object objectTarget) {
        // 为目标对象target赋值
        this.target = objectTarget;
        Enhancer enhancer = new Enhancer();
        // 设置父类,因为CGLIB是针对指定的类生成一个子类，所以需要指定父类
        enhancer.setSuperclass(objectTarget.getClass());
        // 设置回调
        enhancer.setCallback(this);
        // 创建并返回代理对象
        Object result = enhancer.create();
        return result;
    }

    public static void main(String[] args) {
        //实例化CglibProxy对象
        CglibProxy cglibProxy = new CglibProxy();
        IUserManager user = (IUserManager) cglibProxy.getCglibProxy(new UserManagerImpl());
        //执行新增方法
        user.addUser("cmg", "123456");
        //执行删除方法
        user.delUser("cmg");
    }
}
